<template>
  <div class="departments-container">
    <el-card class="departments-card">
      <template #header>
        <div class="card-header">
          <span>部门管理</span>
          <el-button type="primary" @click="handleAdd">新增部门</el-button>
        </div>
      </template>
      
      <el-table
        :data="departmentList"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="部门名称" />
        <el-table-column prop="code" label="部门编码" width="120" />
        <el-table-column prop="manager" label="部门主管" width="120" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="employeeCount" label="员工人数" width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleAddSub(row)">添加子部门</el-button>
            <el-button type="primary" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增部门' : '编辑部门'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="departmentForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级部门">
          <el-tree-select
            v-model="departmentForm.parentId"
            :data="departmentOptions"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择上级部门"
            check-strictly
            :disabled="!!currentParentId"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="departmentForm.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="部门主管" prop="manager">
          <el-input v-model="departmentForm.manager" placeholder="请输入部门主管" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="departmentForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getDepartmentList, addDepartment, updateDepartment, deleteDepartment, type DepartmentData } from '@/api/departments'

interface Department {
  id: number
  name: string
  code: string
  manager: string
  phone: string
  employeeCount: number
  createTime: string
  parentId?: number
  children?: Department[]
}

const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentParentId = ref<number | null>(null)
const formRef = ref<FormInstance>()

const departmentForm = reactive({
  id: 0,
  parentId: null as number | null,
  name: '',
  code: '',
  manager: '',
  phone: ''
})

const rules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入部门编码', trigger: 'blur' }],
  manager: [{ required: true, message: '请输入部门主管', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
}



const departmentList = ref<Department[]>([])
const departmentOptions = ref<Department[]>([])

// 将扁平列表转换为树形结构
function buildTree(departments: Department[]): Department[] {
  const map = new Map<number, Department>()
  const tree: Department[] = []
  
  // 创建映射
  departments.forEach(dept => {
    map.set(dept.id, { ...dept, children: [] })
  })
  
  // 构建树结构
  departments.forEach(dept => {
    const node = map.get(dept.id)
    if (node && dept.parentId) {
      const parent = map.get(dept.parentId)
      if (parent) {
        parent.children!.push(node)
      }
    } else if (node) {
      tree.push(node)
    }
  })
  
  return tree
}

// 加载部门数据
async function loadDepartments() {
  loading.value = true
  try {
    const flatList = await getDepartmentList()
    const treeData = buildTree(flatList)
    departmentList.value = treeData
    departmentOptions.value = flatList // 用于表单选择的扁平列表
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadDepartments()
})

function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(departmentForm, {
    id: 0,
    parentId: null,
    name: '',
    code: '',
    manager: '',
    phone: ''
  })
}

function handleAdd() {
  dialogType.value = 'add'
  currentParentId.value = null
  resetForm()
  dialogVisible.value = true
}

function handleAddSub(row: Department) {
  dialogType.value = 'add'
  currentParentId.value = row.id
  resetForm()
  departmentForm.parentId = row.id
  dialogVisible.value = true
}

function handleEdit(row: Department) {
  dialogType.value = 'edit'
  Object.assign(departmentForm, {
    id: row.id,
    parentId: row.parentId,
    name: row.name,
    code: row.code,
    manager: row.manager,
    phone: row.phone
  })
  dialogVisible.value = true
}

function handleDelete(row: Department) {
  if (row.children?.length) {
    ElMessage.warning('该部门下还有子部门，不能删除')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除该部门吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await deleteDepartment(row.id)
      ElMessage.success('删除成功')
      loadDepartments() // 重新加载数据
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await addDepartment({
        name: departmentForm.name,
        code: departmentForm.code,
        manager: departmentForm.manager,
        phone: departmentForm.phone,
        employeeCount: 0,
        parentId: departmentForm.parentId || null
      })
      ElMessage.success('新增成功')
    } else {
      await updateDepartment({
        id: departmentForm.id,
        name: departmentForm.name,
        code: departmentForm.code,
        manager: departmentForm.manager,
        phone: departmentForm.phone,
        employeeCount: 0,
        createTime: '',
        parentId: departmentForm.parentId || null
      })
      ElMessage.success('编辑成功')
    }
    dialogVisible.value = false
    loadDepartments() // 重新加载数据
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.departments-container {
  padding: 20px;
}

.departments-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}
</style>